package com.kehutong.common.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.coraframework.util.Objects;

public class TreeUtil {

    /**
     * 将TreeEntity按ID转为Map
     * @param list
     * @return
     */
    public static <T extends ITree<T>> Map<String, T> asMapById(List<T> list) {
        Map<String, T> map = new LinkedHashMap<>();
        
        if (Objects.nonEmpty(list)) {
            for (T entity : list) {
                map.put(entity.getId(), entity);
            }
        }
        
        return map;
    }
    
    /**
     * <pre>将菜单列表组织为菜单树</pre>
     *
     * @param topElement
     * @param list
     * @return
     */
    public static <T extends ITree<T>> T  organizeAsTree(List<T> treeList, boolean sortAble) {
    	if (sortAble) {
    		Collections.sort(treeList);
    	}
    	
    	Map<String, T> treeMap = asMapById(treeList);
    	return organizeAsTree(treeMap, treeList);
    }
    
    /**
     * <pre>将菜单列表组织为菜单树</pre>
     *
     * @param topElement
     * @param list
     * @return
     */
    public static <T extends ITree<T>> T organizeAsTree(Map<String, T> treeMap, boolean sortAble) {
    	List<T> treeList = new ArrayList<>(treeMap.size());
    	treeMap.forEach((k, v)->treeList.add(v));
    	
    	if (sortAble) {
    		Collections.sort(treeList);
    	}

    	return organizeAsTree(treeMap, treeList);
    }
    
    /**
     * <pre>将菜单列表组织为菜单树</pre>
     *
     * @param topElement
     * @param list
     * @return
     */
    public static <T extends ITree<T>> Map<String, T>  organizeAsTree(List<T> treeList) {
    	Map<String, T> treeMap = asMapById(treeList);
    	for (T item : treeList) {
			T parent = treeMap.get(item.getPid());
			if (Objects.nonNull(parent)) {
				parent.addChild(item);
			}
    	}

    	return treeMap;
    }
    
    private static <T extends ITree<T>> T  organizeAsTree(Map<String, T> treeMap, List<T> treeList) {
    	for (T item : treeList) {
			T parent = treeMap.get(item.getPid());
			if (Objects.nonNull(parent)) {
				parent.addChild(item);
			}
    	}

    	return treeMap.get(Root.ROOT_ID);
    }

}
